<template>
  <q-page>
    <q-inner-loading visible v-if="model.id == 0">
      <q-spinner-gears size="50px" color="primary"></q-spinner-gears>
      <b class="text-primary">数据加载中...</b>
    </q-inner-loading>  
    <my-event-toolbar v-model="model" />
    <div class="row gutter-sm" :style="$q.platform.is.desktop?'padding:8px;':''">

      <!-- base content -->
      <div class="col-xs-12 col-md-6">
        <my-event-info v-model="model" v-if="model.id>0" />
      </div>

      <!-- user list -->
      

      <div class="col-xs-12 col-md-6" v-if="model.id>0">

        <q-list separator dense class="q-py-none" :no-border="$q.platform.is.mobile">
          <q-list-header class="row">
            <div class="col">中奖用户</div>
            <div class="col-auto">
              <q-btn v-if="!readonly" class="q-mx-sm" 
                dense outline label="发送中奖通知" color="secondary"  @click="wechatNotify()"></q-btn>

              <q-btn v-if="!readonly" dense label="上传中奖名单" color="primary"  @click="uploadPlay($event)">
                <input type="file" style="display:none;"/> 
              </q-btn>

              <q-btn v-if="list.length>0" class="q-mx-sm" 
                dense outline label="下载中奖名单" color="black"  @click="downloadPlay()"></q-btn>
            </div>
          </q-list-header>
          
          <template  v-if="list.length>0">
            <q-tabs class="col-xs-12 col-md-10" align="justify" inverted v-if="model.id>0&&list.length>0">
              <!-- 选项卡 - 注意slot="title" -->
              <q-tab slot="title" label="全部"  @select="select(null)"  />
              <q-tab slot="title" label="未回应"  @select="select('')" default  :count="unknownCount" name="tab-2"/>
              <q-tab slot="title" label="确认来"  @select="select('confirm')"   :count="confirmedCount"/>
              <q-tab slot="title" label="已请假"  @select="select('leave')"   :count="leavedCount"/>

              <q-tab-pane name="tab-2" v-if="unknownCount > 0">
                <q-btn dense color="primary" label="创建二次确认短信" @click="createSms()" />
              </q-tab-pane>
            </q-tabs>
            <q-item style="padding:0;">
              <q-search icon="mdi-account-search" class="full-width no-shadow" :value="filter" 
                  inverted-light color="grey-2"
                placeholder="通过昵称及手机号搜索" autofocus="true"
                @input="filterUser" @clear="filterUser('')" clearable/>
            </q-item>
            <q-item v-for="(item, idx) in filteredList" :key="'user_'+item.id">
              <!-- <q-item-side :avatar="item.avatar" /> -->
              <q-item-main label>
                <q-item-tile label><a :href="'https://www.douban.com/people/'+item.id+'/'" target="_blank">{{item.name}}</a></q-item-tile>
                <q-item-tile sublabel>{{item.phone == '0' ? '' : item.phone}}</q-item-tile>
              </q-item-main>     
              <q-item-side right>
                <q-btn v-if="!readonly && item.confirmStatus==''" 
                    dense color="black" icon="mdi-account-remove" label="移除" 
                    @click="removePlayer(item, idx)" />

                <q-btn v-if="item.confirmStatus==''" 
                    dense color="orange" label="请假" 
                    @click="confirmPlayer(item, 'leave')" />
              </q-item-side> 

              <q-item-side right v-if="!readonly">

                <q-btn v-if="item.confirmStatus==''" 
                    dense color="green" label="确认" icon="mdi-check-circle" 
                    @click="confirmPlayer(item, 'confirm')" />

                <q-btn-dropdown  v-if="!readonly && item.confirmStatus!=''" 
                  dense outline icon="mdi-check-circle" 
                  :label="item.confirmStatus=='confirm'?'确认来':'已请假'" 
                  :color="item.confirmStatus=='confirm'?'green':'orange'">
                  <!-- 下拉内容 -->
                  <q-list separator class="q-pa-none" style="min-width:100px;">
                    <q-item class="q-pa-none">
                      <q-btn icon="mdi-restore" class="full-width" dense flat 
                          :color="item.confirmStatus=='confirm'?'green':'orange'" v-close-overlay
                          label="重新确认" @click="confirmPlayer(item, '')" />
                    </q-item>
                  </q-list>
                </q-btn-dropdown> 

              </q-item-side>
            </q-item>
          </template>
          <q-item v-if="list.length<=0&&!readonly">
            <q-item-main>还未上传中奖名单</q-item-main>
          </q-item>
        </q-list>

      </div>      
    </div>
    <!-- player add -->
    <q-btn round color="primary" size="lg" class="fixed"
      icon="mdi-plus" style="right: 15px; bottom: 60px"
      @click="modal = true" v-if="!readonly"/>

    <!-- modal -->
    <q-modal v-model="modal" :position="$q.platform.is.mobile?'':'right'" :maximized="$q.platform.is.mobile">      
      <q-tabs align="justify" inverted style="min-height:800px;">
        <q-tab slot="title" name="tab-1" label="搜索添加" default />
        <q-tab slot="title" name="tab-2" label="手工添加" />
        <q-tab slot="title" name="tab-3" label="批量添加" />
        <q-tab-pane name="tab-1" class="q-pa-none">
          <q-list dense no-border class="q-pa-none">
            <q-btn class="float-right" flat round icon="mdi-close" @click="modal=false"/>
            <q-list-header></q-list-header>
            <q-item>
              <q-search icon="mdi-account-search" class="full-width" :value="query" color="primary" 
                placeholder="通过豆瓣ID、昵称及手机号搜索" autofocus="true"
                @change="searchUser" />
            </q-item>
            <q-item v-if="results.length==0 && query.length>0">
              <q-item-main><b class="text-primary">没有符合条件的用户...</b></q-item-main>
            </q-item>
            <q-item v-for="item in results" :key="'search_user_'+item.id">
              <!-- <q-item-side :avatar="item.avatar" /> -->
              <q-item-main>
                <q-item-tile label>{{item.name}}</q-item-tile>
                <q-item-tile sublabel>{{item.phone > 0 ? item.phone : ''}}</q-item-tile>
              </q-item-main>
              <q-item-side right>
                <q-btn flat round color="primary" icon="mdi-plus" @click="addPlayer(item)"/>
              </q-item-side>
            </q-item>
          </q-list>
        </q-tab-pane>
        <q-tab-pane name="tab-2" class="q-pa-none">
          <q-list dense no-border class="q-pa-none">
            <q-btn class="float-right" flat round icon="mdi-close" @click="modal=false"/>
            <q-list-header></q-list-header>
            <q-item>
              <q-input class="full-width" :before="[{icon: 'mdi-account'}]" type="number" v-model="input.id" placeholder="豆瓣ID(必填)" />
            </q-item>
            <q-item>
              <q-input class="full-width" :before="[{icon: 'mdi-phone'}]" type="number" v-model="input.phone" placeholder="手机号" />
            </q-item>
            <q-item>
              <q-btn color="primary" class="full-width q-my-sm" icon="mdi-plus" label="添加" @click="savePlayer" />
            </q-item>
          </q-list>
        </q-tab-pane>
        <q-tab-pane name="tab-3" class="q-pa-none">
          <q-list dense no-border class="q-pa-none">
            <q-btn class="float-right" flat round icon="mdi-close" @click="modal=false"/>
            <q-list-header><small class="text-primary">(可直接复制Excel表中的[豆瓣ID]列)</small></q-list-header>
            <q-item>
              <q-input class="full-width" type="textarea" rows="4" :max-height="100" v-model="input.ids"
                  placeholder="输入多位用户的豆瓣ID，以逗号或换行分割" />
            </q-item>
            <q-item>
              <q-btn color="primary" class="full-width q-my-sm" icon="mdi-plus" label="批量添加" @click="savePlayers" />
            </q-item>
          </q-list>
        </q-tab-pane>
      </q-tabs>
    </q-modal>
  </q-page>
</template>

<script>
import MyEventToolbar from "../components/MyEventToolbar.vue";
import MyEventInfo from "../components/MyEventInfo.vue";

export default {
  name: 'PageEventPlay',
  components: { MyEventToolbar, MyEventInfo },
  data () {
    return {
      selected: null,
      readonly: true,
      modal: false,
      query: '',
      filter: '',
      input: {
        id: '',
        phone: '',
        ids: '',
      },
      results: [],
      model: {
        step: 0,
        name: '',
        id: 0,
        days: 0,
        date: '',
        time: '',
        place: '',
        city: '',
        movieId: 0,
        movieName: '',
        userCount: 0,
        hasExcel: false,
        ratingCount: 0,
        stars: [0,0,0,0,0],
        starsRate: [0,0,0,0,0],
        score: '',
        modal:true
      },
      list:[]
    }
  },
  mounted() {    
    let me = this;
    this.loadEventPlay();
    this.refreshPlayers();
    this.$api.ui.pageBackBtn = function(){
      me.$router.push('/event');
    }
  },
  methods: {
    initCheckBeforeMinutes() {
      let me = this;
      this.$q.dialog({
        title: '签到时间确认',
        message: '开场前多少分钟开始签到？',
        prompt: {
          model: '70',
          type: 'number' // 可选的
        },
        cancel: true,
        color: 'secondary'
      }).then(data => {
        me.model.checkBeforeMinutes = data;
        me.$api.party.updateCheckTime(me.model.id, data);
      }).catch(() => {
        
      })
    },
    // 创建二次确认短信
    createSms() {
      let me = this;
      let name = '《' + me.model.movieName + '》' + me.model.city;
      let sms = { 
        noticeId : 0, 
        config: '692991',
        title: name + '活动-二次确认短信', 
        content: '活动提醒：你好，你参加${movie}已获得活动名额，请您尽快在线确认是否参加，一小时内不确认名额无效。确认地址：https://w.url.cn/s/AomPfya~@~' + name, 
        userIds: '', 
        params:[], 
        channel: 'QCLOUD'  
      };

      // 拼接手机号
      let phones = "";
      this.list.forEach(item=>{
        if(item.confirmStatus == '' && item.phone.length == 11) {
          phones += ("\n" + item.phone)
        };
      });
      sms.userIds = phones.substring(1);

      // 保存短信
      me.$api.notice.saveSmsCode(sms, res=>{
        let id = res.data.model.noticeId;
        me.$router.push('/sms-code/view2/' + id);
      }, err=>{});
    },

    select(type) {
      this.selected = type;
    },

    refreshPlayers() {
      let me = this;
      let eventId = me.$route.params.id;
      this.$api.party.loadEventPlayers(eventId, res=>{
        me.list = res.data.model;
      });
    },

    savePlayer() {
      if(this.input.id > 0) {
        let me = this;
        let eventId = me.$route.params.id;
        me.modal = false;
        me.$api.party.addPlayer(eventId, {"id":me.input.id,"phone":me.input.phone}, res=>{
          me.list.unshift(res.data.model);
          me.model.userCount++;
          // input restore
          me.input.id = '';
          me.input.phone = '';
        });
      }
    },

    savePlayers() {
      if(this.input.ids.length > 0) {
        let me = this;
        let eventId = me.$route.params.id;
        me.modal = false;
        me.$api.party.addPlayers(eventId, me.input.ids, res=>{
          res.data.model.forEach(player=>{me.list.unshift(player)});
          me.model.userCount+=res.data.model.length;
          // input restore
          me.input.ids = '';
        });
      }
    },

    addPlayer(item) {
      let me = this;
      let eventId = me.$route.params.id;
      me.modal = false;
      me.$api.party.addPlayer(eventId, item, res=>{
        me.list.unshift(res.data.model);
        me.model.userCount++
        // search restore
        me.query = '';
        me.results = [];
      });
    },

    confirmPlayer(item, status) {
      let me = this;
      let eventId = me.$route.params.id;
      me.$api.party.confirmPlayer(eventId, item, status, res=>{
        item.confirmStatus = status;
      });
    },

    removePlayer(item, idx) {
      let me = this;
      let eventId = me.$route.params.id;
      me.$api.party.removePlayer(eventId, item, res=>{
        me.list.splice(idx, 1);
        me.model.userCount--;
      });
    },

    filterUser(val) {
      this.filter = val;
    },

    searchUser(val) {
      if(val.trim().length > 0) {
        let me = this;
        me.$api.search.searchUser(val.trim(), res=>{
          me.results = res.data.model;
          me.query = val;
        })
      } else {
        this.query = val;
      }
    },

    loadEventPlay() {
      let me = this;
      let eventId = me.$route.params.id;
      this.$api.party.loadEvent(eventId, res=>{
        me.model = res.data.model;
        if(me.model.checkBeforeMinutes == 65) {
          me.initCheckBeforeMinutes();
        }

        me.$api.ui.pageTitle = me.model.city + '：《' + me.model.movieName + '》';
        // check readonly
        if(me.model.step == 0 || me.model.step == 4) {
          // step over or summary
          me.readonly = true;
        } else {
          me.readonly = false;
        }
      });
    },

    uploadPlay(e) {
      let me = this;
      let inputNode = e.target.parentElement.getElementsByTagName("input")[0];
      inputNode.onchange = function(){
        let file = inputNode.files[0];
        me.$api.party.uploadExcelPlay(me.model.id, file, res=>{
          if(res.data.ret == 200) {
            me.model.hasExcel = true;
            let result = res.data.model;
            me.loadEventPlay();
            me.refreshPlayers();
            if(result.duplicateCount > 0 || result.invalidCount > 0) {
              let msg = '';
              if(result.duplicateCount > 0) {
                msg += ('有' + result.duplicateCount + '个重复豆瓣ID：【' + result.duplicateIds + '】；    ');
              }
              if(result.invalidCount > 0) {
                msg += ('有' + result.invalidCount + '个无效豆瓣ID：【' + result.invalidIds + '】；    ');
              }
              msg += ('实际提交数据：' + result.validCount + '条');
              me.$q.dialog({
                title: '注意',
                message: msg
              });
            }
            else {
              let msg = '';
              msg += ('中奖人数：【' + result.validCount + '人】； ');
              msg += '是否将中奖信息推送给预约用户？';
              me.$q.dialog({
                title: '中奖人数确认',
                message: msg,
                ok: '确定(立即推送)',
                cancel: '取消'
              }).then(() => {
                me.wechatNotify();
              }).catch(() => {
                // cancel 
              })
            }
          }
        })
      };
      inputNode.click();
    },
    downloadPlay() {
      let filename = this._generateFileName('中奖用户表');
      this.$api.party.downloadExcelPlay(this.model.id, filename);
    },
    downloadRated() {
      let filename = this._generateFileName('评分表');
      this.$api.party.downloadExcelRated(this.model.id, filename);
    },

    downloadNotRated() {
      let filename = this._generateFileName('催分表');
      this.$api.party.downloadExcelNotRated(this.model.id, filename);
    },

    openModal() {
      console.log('open');
    },

    _generateFileName(type) {
      var model = this.model;
      return model.date.replace('-', '').replace('-','') + '_' 
                        + model.city + '_' 
                        + model.movieName + '_'
                        + type 
                        +'.xls';
    },

    wechatNotify() {
      let me = this;
      let eventId = me.$route.params.id;
      this.$api.party.miniNotify(eventId, res=>{
        me.$q.notify({
                message: '消息推送完成',
                type: 'positive',
                color: 'positive',
                icon: 'mdi-check'
              });
      });
    }
  },
  computed: {
    filteredList() {
      let query = this.filter.toLowerCase();
      let selected = this.selected;
      return this.list.filter(function (user) {
        if(selected != null && selected != user.confirmStatus) {
          return false;
        }

        if(query.length>0) {
          let text =  user.phone + user.name.toLowerCase();
          if(text.indexOf(query)>=0) {
            return true;
          }       
          return false;
        }
        return true;
      })
    },
    confirmedCount() {
      let count = 0;
      this.list.forEach(item=>{
        if(item.confirmStatus == 'confirm') count++;
      });
      return count + '';
    },
    leavedCount() {
      let count = 0;
      this.list.forEach(item=>{
        if(item.confirmStatus == 'leave') count++;
      });
      return count + '';
    },
    unknownCount() {
      let count = 0;
      this.list.forEach(item=>{
        if(item.confirmStatus == '') count++;
      });
      return count + '';
    }
  }
}
</script>
